$.getUrlParam = function (name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]); return null;
};
//复选框非空
function cbrequired(obj){
	if($('input[name="'+$(obj).attr("name")+'"]:checked').length<=0){
		$($('input[name="'+$(obj).attr("name")+'"]')[0]).prop('required','required');
	}else{
		$('input[name="'+$(obj).attr("name")+'"]').removeProp('required');
	}
}
/*选项索引键值对*/
var optionsKey={
		"1":"A","2":"B","3":"C","4":"D","5":"E","6":"F","7":"G","8":"H","9":"I","10":"J","11":"K","12":"L","13":"M","14":"N","15":"O","16":"P","17":"Q","18":"R","19":"S","20":"T","21":"U","22":"V","23":"W","24":"X","25":"Y","26":"Z"
};
/*填空宽度控制*/
var textWidth = function(text){ 
    var sensor = $('<pre>'+ text +'</pre>').css({display: 'none'}); 
    $('body').append(sensor); 
    var width = sensor.width();
    sensor.remove();
    return width;
};
function changeText(obj){
    $(obj).width(textWidth($(obj).val())+30);
}
/*生成唯一num*/
function newGuid()  
{  
    var guid = "";  
    for (var i = 1; i <= 32; i++){
      var n = Math.floor(Math.random()*16.0).toString(16);  
      guid +=   n;  
      if((i==8)||(i==12)||(i==16)||(i==20))  
        guid += "-";  
    }  
    return guid;      
}

var E = window.wangEditor;
var editor = new E('#content-toolbar','#content');
$(function(){
	/* 创建编辑器  */
	editor.customConfig.uploadImgMaxSize = 6 * 1024 * 1024;
	editor.customConfig.uploadImgMaxLength = 5;
	editor.customConfig.uploadFileName = 'myFileName';
	editor.customConfig.uploadImgHeaders = {
	       'Accept' : 'multipart/form-data'
	   };
	editor.customConfig.menus = [//定义菜单
		'head',
		'image'
	];
	editor.customConfig.uploadImgServer = '/exam/files/upload';
	editor.customConfig.showLinkImg = false;
	editor.create();
	
	 $(".selectpicker").selectpicker({  
	        noneSelectedText : '请选择'  
	        });  
	  
	        $(window).on('load', function() {  
	        $('.selectpicker').selectpicker('val', '');  
	        $('.selectpicker').selectpicker('refresh');  
	        });  
	  
	        // 下拉数据加载
	    $.ajax({
	        type : 'get',  
	        url :"teacher/getSubjects",  
	        dataType : 'json',  
	        success : function(datas) {// 返回list数据并循环获取
	            var select = $("#slpk");  
	            for (var i = 0; i < datas.length; i++) {  
	                select.append("<option value='"+datas[i].id+"'>"  
	                        + datas[i].name + "</option>");  
	            }  
	            $('.selectpicker').selectpicker('val', '');  
	            $('.selectpicker').selectpicker('refresh'); 
	            
	          //加载完选项再加载编辑信息
	            var id = $.getUrlParam('id');
	            if(id!=null&&id!=""){
	            	//加载信息
	            	$.ajax({
	            		url:'multiple/findOne',
	            		type:'post',
	            		dataType:'json',
	            		data:{id:id},
	            		success:function(data){
	            			if(null!=data){
	            				//加载题目信息
	            				$('#id').val(data.id);
	            				$('#num').val(data.num);
	            				if(data.subject!=null)
	            					$('.selectpicker').selectpicker('val', data.subject.id);
	            				editor.txt.html(data.title);
	            				var length = Object.keys(data.options).length;
	            				for(var i=0;i<length;i++){
	            					var option = data.options[optionsKey[i+1]];
	            					var optionHtml = "";
	            					optionHtml += '<div class="form-group option-item">'+
	            								'<input type="hidden" class="option-id" value='+option.id+'>'+
	            								'<input type="hidden" class="option-num" value="'+option.num+'">'+
	            								'<label class="col-sm-1 control-label"><span class="option-index">'+optionsKey[i+1]+'</span>&nbsp;';
	            					var flag = false;
	            					for(var j=0;j<data.answers.length;j++){
	            						if(data.answers[j].id==option.id){
	            							flag=true;
	            						}
	            					}
	            								if(flag)
	            									optionHtml += '<input checked ';
	            								else
	            									optionHtml += '<input ';
	            					optionHtml += 'onchange="cbrequired(this)" type="checkbox" name="answerKey" value="'+optionsKey[i+1]+'"></label>'+
	            								'<div class="col-sm-10">'+
	            									'<div id="toolbar'+optionsKey[i+1]+'" class="toolbar">'+
	            									'</div>'+
	            									'<div id="text'+optionsKey[i+1]+'" class="text">'+
	            								    '</div>'+
	            								 '</div>'+
	            							'</div>';
	            					$("#option-container").append(optionHtml);
	            					var optionsE = window.wangEditor;
	            					var editorO = new optionsE('#toolbar'+optionsKey[i+1],'#text'+optionsKey[i+1]);
	            					editorO.customConfig.uploadImgMaxSize = 6 * 1024 * 1024;
	            					editorO.customConfig.uploadImgMaxLength = 5;
	            					editorO.customConfig.uploadFileName = 'myFileName';
	            					editorO.customConfig.uploadImgHeaders = {
	            					       'Accept' : 'multipart/form-data'
	            					   };
	            					editorO.customConfig.menus = [//定义菜单
	            						'image',
	            						'quote'
	            					];
	            					editorO.customConfig.uploadImgServer = '/exam/files/upload';
	            					editorO.customConfig.showLinkImg = false;
	            					editorO.create();
	            					editorO.txt.html(option.content);
	            				}
	            			}else{
	            				window.location.href="/exam/tch_single";
	            			}
	            		},
	            		error:function(){
	            			Modal.alert({msg:'出错！'});
	            			window.location.href="/exam/tch_single";
	            		}
	            	});
	            }
	        }  
	    });
})


/*添加选项事件*/
function addOption(){
	//1 获取到已存在的选项
	var options = $("#option-container").find(".option-item");
	//当前选项索引optionsKey[options.length+1]
	var html = "";
	html += '<div class="form-group option-item">'+
				'<input type="hidden" class="option-id">'+
				'<input type="hidden" class="option-num">'+
				'<label class="col-sm-1 control-label"><span class="option-index">'+optionsKey[options.length+1]+'</span>&nbsp;<input onchange="cbrequired(this)" type="checkbox" name="answerKey" value="'+optionsKey[options.length+1]+'"></label>'+
				'<div class="col-sm-11">'+
					'<div id="toolbar'+optionsKey[options.length+1]+'" class="toolbar">'+
					'</div>'+
					'<div id="text'+optionsKey[options.length+1]+'" class="text"> <!--可使用 min-height 实现编辑区域自动增加高度-->'+
				    '</div>'+
				 '</div>'+
			'</div>';
	$("#option-container").append(html);
	
	var optionsE = window.wangEditor;
	var editorO = new optionsE('#toolbar'+optionsKey[options.length+1],'#text'+optionsKey[options.length+1]);
	editorO.customConfig.uploadImgMaxSize = 6 * 1024 * 1024;
	editorO.customConfig.uploadImgMaxLength = 5;
	editorO.customConfig.uploadFileName = 'myFileName';
	editorO.customConfig.uploadImgHeaders = {
	       'Accept' : 'multipart/form-data'
	   };
	editorO.customConfig.menus = [//定义菜单
		'head',
		'image',
		'quote'
	];
	editorO.customConfig.uploadImgServer = '/exam/files/upload';
	editorO.customConfig.showLinkImg = false;
	editorO.create();
	
}
/*删除选项*/
function deleteOption(obj){
	if(confirm("确定要删除选项?")){
		var item = $(obj).parents('.option-item');
		var prev = item.prevAll('.option-item');
		var afte = item.nextAll('.option-item');
		for(var i=0;i<afte.length;i++){
			//删除前设置下级兄弟元素的索引
			var option_index = $(afte[i]).find('.option-index');
			$(option_index[0]).text(optionsKey[prev.length+i+1]);
			//设置id
			var toolbar = $(afte[i]).find('.toolbar');
			var text = $(afte[i]).find('.text');
			$(toolbar).prop("id","toolbar"+optionsKey[prev.length+i+1]);
			$(text).prop("id","text"+optionsKey[prev.length+i+1]);
		}
		//删除该选项
		$(item).remove();
	}
}
/* 下拉选择科目加载后台信息 */
/* 多选题信息提交 */
$("#multipleForm").submit(function(event){
	/*private Long id;
	private String title;
	private String num;
	private Subject subject;
	private Map<String, Options> options = new HashMap<String, Options>();
	private Options answer;*/
	var multiple = {};
	var options = {};
	
	var id = $('#id').val();
	var num = $('#num').val();
	$(multiple).attr("id",id);
	$(multiple).attr("num",num);
	
	var subject = {};
	var subjectId = $('#slpk option:selected').val();
	$(subject).attr("id",subjectId);
	$(multiple).attr("subject",subject);
	
	//获取题干
	var title = editor.txt.html();
	if(title==null||title==""||title=="<p><br></p>"){
		alert("题干不能为空！");
		return false;
	}
	$(multiple).attr("title",title);
	
	//获取选项
	var items = $('.option-item');
	if(items.length<=0){
		alert("请添加选项!");
		return false;
	}
	for(var i=0;i<items.length;i++){
		var input = $(items[i]).find('.w-e-text');
		
		var keyElement = $(items[i]).find('.option-index');
		var key = $(keyElement).text();
		if($(input[0]).html()==""||$(input[0]).html()=="<p><br></p>"){
			alert("选项的内容不能为空!");
			return false;
		}
		var option = {};
		var option_id = $(items[i]).find('.option-id').val();
		var option_num= $(items[i]).find('.option-num').val();
		if(option_num==""||option_num==null)
			option_num = newGuid();
		$(option).attr("content",$(input[0]).html());
		$(option).attr("id",option_id);
		$(option).attr("num",option_num);
		$(options).attr(key,option);
	}
	$(multiple).attr("options",options);
	
	//获取正确选项的key
	var answerKey = new Array();
	if($('input[name="answerKey"]:checked').length<=0){
		alert("请选择至少一个选项！");
		return false;
	}
	$('input[name="answerKey"]:checked').each(function(){ 
		answerKey.push($(this).val()); 
	});
	
	var result = JSON.stringify(multiple);
	
	$.ajax({
		url:'multiple/saveOrUpdate',
		type:'post',
		dataType:'json',
		data:{multiple:result,answerKey:answerKey},
		success:function(data){
			alert(data.msg);
			if(data.success)
				window.location.reload();
		},
		error:function(){
			alert("出错！");
		}
	});
	
	return false;
});
/*表单校验*/
/*test*/
function test(){
	var blank = {};
	var blanks = {};
	
	var id = $('#id').val();
	var num = $('#num').val();
	
	var inputs = $('.the-blank');
	for(var i=0;i<inputs.length;i++){
		$(blanks).attr((i+1),inputs[i].value);
	}
	console.log(JSON.stringify(blanks));
	
	var content = editor.txt.html();
	console.log(content);
	$("body").append(content);
	alert($('#slpk option:selected').val());
}